package com.example.demo.config;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.orm.hibernate5.HibernateTemplate;
import org.springframework.orm.hibernate5.LocalSessionFactoryBean;
import org.springframework.orm.hibernate5.support.OpenSessionInViewFilter;

import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;
import java.util.Properties;

@Configuration
public class HibernateConfig {


    @Bean
    public LocalSessionFactoryBean sessionFactory(DataSource dataSource, ApplicationContext ctx) {
        LocalSessionFactoryBean localSessionFactory = new LocalSessionFactoryBean();
        localSessionFactory.setDataSource(dataSource);
        localSessionFactory.setPackagesToScan("com.example.demo.model");

        //hibernate属性配置
        Properties prop = new Properties();
        prop.put("hibernate.show_sql",true);
        prop.put("format_sql",true);
        prop.put("hibernate.hbm2ddl.auto","update");
        localSessionFactory.setHibernateProperties(prop);
        return localSessionFactory;
    }

    @Bean
    public HibernateTemplate hibernateTemplate(LocalSessionFactoryBean localSessionFactory){
        HibernateTemplate hibernateTemplate = new HibernateTemplate();
        hibernateTemplate.setSessionFactory(localSessionFactory.getObject());
        return hibernateTemplate;
    }



}
